//
//  LoginVC.m
//  EPTool
//
//  Created by guoshiqing on 2018/4/9.
//  Copyright © 2018年 云数动能科技. All rights reserved.
//

#import "LoginVC.h"
#import "Macro.h"
#import "UIView+DDAddition.h"
#import "UIImageView+WebCache.h"
#import "AreaCodeView.h"
#import "LoginVC.h"
#import "EPButton.h"
#import "AccountView.h"
#import "PasswordView.h"
#import "StringUtil.h"

#import "UserCacheInfoModel.h"
#import "MobileInputVC.h"
#import "NotificationHelp.h"
#import "AccountSysVM.h"
#import "UserInfoModel.h"
#import "ToastView.h"
#import "CommonHelper.h"
#import "NotificationHelp.h"
#import "UserSettings.h"
#import "ErrorCode.h"

#import <UMShare/UMShare.h>
//#import <FBSDKLoginKit/FBSDKLoginKit.h>

@interface LoginVC () <UITextFieldDelegate>


// 用户密码当前的长度
@property (nonatomic, assign) NSInteger lenOfAccount;
@property (nonatomic, assign) NSInteger lenOfPwd;

// 界面上大块区域
@property (nonatomic, strong) UIView *avatarBKView;
@property (nonatomic, strong) UIView *helloBKView;
@property (nonatomic, strong) AccountView *accountView;
@property (nonatomic, strong) PasswordView *passwordView;
@property (nonatomic, strong) UIView *loginBKView;

// 头像区域
@property (nonatomic, strong) UIImageView *imgAvatar;
@property (nonatomic, strong) UIButton *btnRegister;

// 欢迎文字区域
@property (nonatomic, strong) UILabel *lblName;
@property (nonatomic, strong) UILabel *lblWelcome;

// 登录按钮区域
@property (nonatomic, strong) EPButton *btnLogin;
@property (nonatomic, strong) UIButton *btnForgotPwd;

// 第三方登录
@property (nonatomic, strong) UIView *SDKTopLine;
@property (nonatomic, strong) UILabel *SDKTopLabel;
@property (nonatomic, strong) UIImageView *SDKWechatBtn;
@property (nonatomic, strong) UIImageView *SDKFBBtn;

// view抬起的高度
@property (nonatomic, assign) CGFloat offSet;
@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 用手机号码获取沙盒中的用户信息
    NSString *account = [self.accountView getAccount];
    NSString *areCode = [self.accountView getAreaCode];
    NSString *strMobile = [account stringByReplacingOccurrencesOfString:@" " withString:@""];
    [self fixAvatarAndNameWithAreaCode:areCode andMobile:strMobile];
    
    [self addSubviews];
    // 添加监听中心
    [self addNotificationCenter];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 修改状态栏文字颜色
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.strMessage && 0 != self.strMessage.length) {
        [self showAlertWithTitle:self.strMessage];
    }
    self.strMessage = @"";
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.view endEditing:YES];
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationDidEnterBackground object:nil];
}

#pragma mark - 监听键盘事件
- (void)addNotificationCenter {
    // 键盘的监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(n_willShowKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(n_willHideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    // 监听转后台通知
    WEAKSELF
    [NotificationHelp addNotification:NotificationDidEnterBackground object:nil usingBlock:^(NSNotification *note) {
        [weakSelf.view endEditing:YES];
    }];
}

- (void)n_willShowKeyboard:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGRect keyboardEndFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    UIView *firstResponder = [keyWindow performSelector:@selector(firstResponder)];
    if ([firstResponder isKindOfClass:[UIView class]]) {
        if (firstResponder.superview == self.accountView) {
            self.view.top += self.offSet;
            self.offSet = 0;
            CGFloat accountMaxY = CGRectGetMinY(self.loginBKView.frame) + self.btnLogin.height;
            if (accountMaxY > keyboardEndFrame.origin.y) {
                self.offSet = accountMaxY - keyboardEndFrame.origin.y;
                self.view.top -= self.offSet;
            }
        }
        else if (firstResponder.superview == self.passwordView)
        {
            self.view.top += self.offSet;
            self.offSet = 0;
            CGFloat pwdMaxY = CGRectGetMinY(self.loginBKView.frame) + self.btnLogin.height;
            if (pwdMaxY > keyboardEndFrame.origin.y) {
                self.offSet = pwdMaxY - keyboardEndFrame.origin.y;
                self.view.top -= self.offSet;
            }
        }
    }
}

- (void)n_willHideKeyboard:(NSNotification *)notification {
    WEAKSELF
    [UIView animateWithDuration:0.25f animations:^{
        UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
        UIView *firstResponder = [keyWindow performSelector:@selector(firstResponder)];
        if ([firstResponder isKindOfClass:[UIView class]]) {
            if (firstResponder.superview == weakSelf.accountView) {
                weakSelf.view.top += weakSelf.offSet;
            }
            else if (firstResponder.superview == weakSelf.passwordView)
            {
                weakSelf.view.top += weakSelf.offSet;
            }
            weakSelf.offSet = 0;
        }
    }];
}

#pragma mark - 接口调用返回结果处理
- (void)handelRequestData:(BaseJSONEntity *)returnValue
{
    [self hideProcessingHud];
    if (0 != returnValue.ret) {
        
        if (C_Login_3TimesError == returnValue.ret) {
            [self showAlertWithMessage:@"" title:returnValue.msg cancelStr:@"否" sureStr:@"是" cancel:^(UIAlertAction * _Nonnull action) {
            } sure:^(UIAlertAction * _Nonnull action) {
                [self btnForgotPwdClick:nil];
            }];
            return;
        }
        if ((C_WXLogin_First == returnValue.ret) && [returnValue.url isEqualToString:WXLoginUrl]) {
            NSDictionary *dic = returnValue.data;
            UserSaveInfo.WXOpenID = dic[@"sOpenId"];
            UserSaveInfo.WXAccessToken = dic[@"sAccessToken"];
            
            MobileInputVC *mbInputVc = [[MobileInputVC alloc] init];
            mbInputVc.baseVM = [[AccountSysVM alloc] init];
            mbInputVc.type = ForBindingMobileTypeFromWX;
            [mbInputVc setAreaCode:[self.accountView getAreaCode] andMobile:[self.accountView getAccount]];
            [self.navigationController pushViewController:mbInputVc animated:YES];
            return;
        }
        if ((C_FBLogin_First == returnValue.ret) && [returnValue.url isEqualToString:FBLoginUrl]) {
            MobileInputVC *mbInputVc = [[MobileInputVC alloc] init];
            mbInputVc.baseVM = [[AccountSysVM alloc] init];
            mbInputVc.type = ForBindingMobileTypeFromFB;
            [mbInputVc setAreaCode:[self.accountView getAreaCode] andMobile:[self.accountView getAccount]];
            [self.navigationController pushViewController:mbInputVc animated:YES];
            return;
        }
        [self showAlertWithTitle:returnValue.msg];
        return;
    }
    
    NSString *areaCode = [self.accountView getAreaCode];
    NSString *account = [self.accountView getAccount];
    UserSaveInfo.areaCode = areaCode;
    UserSaveInfo.mobile = account;
    UserSaveInfo.token = [returnValue.data objectForKey:@"d-tk"];
    [NotificationHelp postNotification:NotificationLoginSuccess object:returnValue.data];
}

#pragma mark - 界面代理方法
// 点击登录
- (void)loginActionWithAreaCode:(NSString *)areaCode andMobile:(NSString *)mobile andPwd:(NSString *)password
{
    [(AccountSysVM *)self.baseVM loginRequestWithAreaCode:areaCode andMobile:mobile andPwd:password];
}

// 点击注册
- (void)registerActionWithAreaCode:(NSString *)areaCode andMobile:(NSString *)mobile
{
    MobileInputVC *mbInputVc = [[MobileInputVC alloc] init];
    mbInputVc.baseVM = [[AccountSysVM alloc] init];
    mbInputVc.type = ForRegisterType;
    [mbInputVc setAreaCode:areaCode andMobile:mobile];
    [self.navigationController pushViewController:mbInputVc animated:YES];
}

// 忘记密码
- (void)fogotActionWithAreaCode:(NSString *)areaCode andMobile:(NSString *)mobile
{
    MobileInputVC *mbInputVc = [[MobileInputVC alloc] init];
    mbInputVc.baseVM = [[AccountSysVM alloc] init];
    mbInputVc.type = ForForgotType;
    [mbInputVc setAreaCode:areaCode andMobile:mobile];
    [self.navigationController pushViewController:mbInputVc animated:YES];
}

//#pragma mark - 添加控件
- (void)addSubviews
{
    self.view.backgroundColor = [UIColor whiteColor];//RGB_BLUE_TEMP;
    
    // 设置大块区域
    [self.view addSubview:self.avatarBKView];
    self.avatarBKView.top = NavBar_Height;
    [self.view addSubview:self.helloBKView];
    self.helloBKView.top = self.avatarBKView.bottom + 13.f;
    [self.view addSubview:self.accountView];
    self.accountView.top = self.helloBKView.bottom + 6.f;
    [self.view addSubview:self.passwordView];
    self.passwordView.top = self.accountView.bottom;
    [self.view addSubview:self.loginBKView];
    self.loginBKView.top = self.passwordView.bottom + 20.f;
    
    // 第三方登录部分
    [self.view addSubview:self.SDKTopLine];
    [self.view addSubview:self.SDKTopLabel];
    if ([[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_WechatSession]) {
        [self.view addSubview:self.SDKWechatBtn];
        if ([[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_Facebook]) {
            [self.view addSubview:self.SDKFBBtn];
        } else {
            self.SDKWechatBtn.centerX = UI_SCREEN_WIDTH / 2;
        }
    } else {
        if ([[UMSocialManager defaultManager] isInstall:UMSocialPlatformType_Facebook]) {
            [self.view addSubview:self.SDKFBBtn];
            self.SDKFBBtn.centerX = UI_SCREEN_WIDTH / 2;
        } else {
            self.SDKTopLine.hidden = YES;
            self.SDKTopLabel.hidden = YES;
        }
    }
    
    // 点击输入框的清除按钮
    WEAKSELF
    self.accountView.btnClearBlock = ^{
        [weakSelf fixAvatarAndNameWithAreaCode:@"" andMobile:@""];
        weakSelf.btnLogin.enabled = NO;
    };
    self.accountView.areaCodeChangeBlock = ^(NSString *strAreaCode, NSString *strMobile) {
        
        [weakSelf fixAvatarAndNameWithAreaCode:strAreaCode andMobile:strMobile];
    };
    self.passwordView.btnClearBlock = ^{
        weakSelf.btnLogin.enabled = NO;
    };
    // 用户编辑状态UITextField长度变化
    self.accountView.txfBecomeBlock = ^(NSInteger length, NSString *mobile, NSString *areaCode) {
        weakSelf.lenOfAccount = length;
        if (MIN_PASSWORD_LENGTH <= weakSelf.lenOfPwd &&
            0 < length) {
            weakSelf.btnLogin.enabled = YES;
        }
        else // 通过光标选择范围的情况
        {
            weakSelf.btnLogin.enabled = NO;
        }
        // 名字和头像匹配
        [weakSelf fixAvatarAndNameWithAreaCode:areaCode andMobile:mobile];
    };
    
    self.passwordView.txfBecomeBlock = ^(NSInteger length) {
        weakSelf.lenOfPwd = length;
        if (MIN_PASSWORD_LENGTH <= length &&
            0 < weakSelf.lenOfAccount) {
            weakSelf.btnLogin.enabled = YES;
        }
        else // 通过光标选择范围的情况
        {
            weakSelf.btnLogin.enabled = NO;
        }
    };
}

#pragma mark - 懒加载
#pragma mark -- 头像 & 注册按钮
- (UIView *)avatarBKView
{
    if (!_avatarBKView) {
        _avatarBKView = [[UIView alloc] initWithFrame:CGRectMake(LoginVC_X, 0, LoginVC_W, 40.f)];
        
        [_avatarBKView addSubview:self.imgAvatar];
        self.imgAvatar.left = 0;
        self.imgAvatar.top = 0;
        [_avatarBKView addSubview:self.btnRegister];
        self.btnRegister.centerY = self.imgAvatar.centerY;
        self.btnRegister.right = _avatarBKView.width;
        self.btnRegister.titleLabel.font = SystemFont(12.f);
        [self.btnRegister setTitle:@"注册" forState:UIControlStateNormal];
        [self.btnRegister addTarget:self action:@selector(btnRegisterClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _avatarBKView;
}

#pragma mark --- 头像
- (UIImageView *)imgAvatar
{
    if (!_imgAvatar) {
        _imgAvatar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40.f, 40.f)];
        _imgAvatar.layer.masksToBounds = YES;
        _imgAvatar.layer.cornerRadius = 20.f;
        _imgAvatar.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _imgAvatar;
}

#pragma mark --- 注册按钮
- (UIButton *)btnRegister
{
    if (!_btnRegister) {
        _btnRegister = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70.f, 40.f)];
        [_btnRegister setTitleColor:[EPColor epColor_Blue] forState:UIControlStateNormal];
    }
    return _btnRegister;
}

#pragma mark -- 欢迎词
- (UIView *)helloBKView
{
    if (!_helloBKView) {
        _helloBKView = [[UIView alloc] initWithFrame:CGRectMake(LoginVC_X, 0, LoginVC_W, 64.f)];
        [_helloBKView addSubview:self.lblName];
        self.lblName.frame = CGRectMake(0, 0, LoginVC_W, _helloBKView.height/2);
        self.lblName.textAlignment = NSTextAlignmentLeft;
        self.lblName.font = SystemFont(23.f);
        self.lblName.textColor = [EPColor epColor_TitleBlack];
        [_helloBKView addSubview:self.lblWelcome];
        self.lblWelcome.frame = CGRectMake(0, _helloBKView.height/2, LoginVC_W, _helloBKView.height/2);
        self.lblWelcome.textAlignment = NSTextAlignmentLeft;
        self.lblWelcome.font = SystemFont(23.f);
        self.lblWelcome.textColor = [EPColor epColor_TitleBlack];
    }
    return _helloBKView;
}

- (UILabel *)lblName
{
    if (!_lblName) {
        _lblName = [[UILabel alloc] init];
    }
    return _lblName;
}

- (UILabel *)lblWelcome
{
    if (!_lblWelcome) {
        _lblWelcome = [[UILabel alloc] init];
    }
    return _lblWelcome;
}

- (void)setWithUserName:(NSString *)userName andAvatarUrl:(NSString *)avatarUrl
{
    if (nil != userName && 0 != userName.length) {
        self.lblName.text = [NSString stringWithFormat:@"Hello! %@", userName];
        self.lblWelcome.text = @"欢迎回来";
    }
    else
    {
        self.lblName.text = @"";
        self.lblWelcome.text = @"欢迎使用动能保险助手";
    }
    
    NSURL *url = [NSURL URLWithString:avatarUrl];
    [self.imgAvatar sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"head40"] options:(SDWebImageRetryFailed | SDWebImageAllowInvalidSSLCertificates)];
}

#pragma mark -- 手机号
- (AccountView *)accountView
{
    if (!_accountView) {
        NSString *format = UserSaveInfo.mobile;
        if ([UserSaveInfo.areaCode isEqualToString:@"86"]) {
            format = [StringUtil stringFormat334:UserSaveInfo.mobile];
        }
        else
        {
            format = [StringUtil stringFormat44:UserSaveInfo.mobile];
        }
        
        NSString *strAreaCode = (0 == UserSaveInfo.areaCode.length)?@"86":UserSaveInfo.areaCode;
        _accountView = [[AccountView alloc] initWithFrame:CGRectMake(LoginVC_X, 0, LoginVC_W, 76.f) andAreaCode:strAreaCode andMobile:format];
        self.lenOfAccount = UserSaveInfo.mobile.length;
        _accountView.textColor = [EPColor epColor_TitleBlack];
    }
    return _accountView;
}

#pragma mark -- 密码区域
- (PasswordView *)passwordView
{
    if (!_passwordView) {
        _passwordView = [[PasswordView alloc] initWithFrame:CGRectMake(LoginVC_X, 0, LoginVC_W, 76.f)];
        _passwordView.textColor = [EPColor epColor_TitleBlack];
    }
    return _passwordView;
}

#pragma mark -- 登录按钮区域
- (UIView *)loginBKView
{
    if (!_loginBKView) {
        _loginBKView = [[UIView alloc] initWithFrame:CGRectMake(LoginVC_X, 0, LoginVC_W, 104.f)];
        
        [_loginBKView addSubview:self.btnLogin];
        [_loginBKView addSubview:self.btnForgotPwd];
        self.btnForgotPwd.top = self.btnLogin.bottom + 20.f;
    }
    return _loginBKView;
}

- (EPButton *)btnLogin
{
    if (!_btnLogin) {
        _btnLogin = [[EPButton alloc] initWithFrame:CGRectMake(0, 0, LoginVC_W, Cell_H)];
        [_btnLogin addTarget:self action:@selector(btnLoginClick:) forControlEvents:UIControlEventTouchUpInside];
        [_btnLogin setTitle:@"登录" forState:UIControlStateNormal];
        [_btnLogin buttonWithStyle:EPBasicButton_btn1];
        _btnLogin.enabled = NO;
    }
    return _btnLogin;
}

- (UIButton *)btnForgotPwd
{
    if (!_btnForgotPwd) {
        _btnForgotPwd = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50.f, 40.f)];
        [_btnForgotPwd addTarget:self action:@selector(btnForgotPwdClick:) forControlEvents:UIControlEventTouchUpInside];
        [_btnForgotPwd setTitle:@"忘记密码" forState:UIControlStateNormal];
        _btnForgotPwd.titleLabel.font = SystemFont(12.f);
        [_btnForgotPwd setTitleColor:[EPColor epColor_Blue] forState:UIControlStateNormal];
    }
    return _btnForgotPwd;
}

#pragma mark - 第三方登录
- (UIView *)SDKTopLine
{
    if (!_SDKTopLine) {
        _SDKTopLine = [[UIView alloc] initWithFrame:CGRectMake(LoginVC_X, 0, LoginVC_W, 1.f)];
        _SDKTopLine.backgroundColor = [EPColor epColor_UnderLine];
        CGFloat space = 20.f;
        if (IS_IPHONE5 || IS_IPHONE4) space = 10.f;
        _SDKTopLine.top = self.loginBKView.bottom + space;
    }
    return _SDKTopLine;
}

- (UILabel *)SDKTopLabel
{
    if (!_SDKTopLabel) {
        _SDKTopLabel = [[UILabel alloc] initWithFrame:CGRectMake(LoginVC_X, 0, 68.f, 17.f)];
        _SDKTopLabel.backgroundColor = [UIColor whiteColor];
        _SDKTopLabel.textColor = [EPColor epColor_Nav];
        _SDKTopLabel.text = @"快速登录";
        _SDKTopLabel.font = SystemFont(12.f);
        _SDKTopLabel.textAlignment = NSTextAlignmentCenter;
        _SDKTopLabel.centerX = UI_SCREEN_WIDTH / 2;
        _SDKTopLabel.centerY = self.SDKTopLine.centerY;
    }
    return _SDKTopLabel;
}

- (UIImageView *)SDKWechatBtn
{
    if (!_SDKWechatBtn) {
        _SDKWechatBtn = [[UIImageView alloc] initWithFrame:CGRectMake(LoginVC_X + Cell_H, 0, Cell_H, Cell_H)];
        _SDKWechatBtn.image = [UIImage imageNamed:@"login_btn_wx"];
        CGFloat space = Cell_H;
        if (IS_IPHONE5 || IS_IPHONE4) space = 24.f;
        _SDKWechatBtn.top = self.SDKTopLine.bottom + space;
        _SDKWechatBtn.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(WechatLogin)];
        [_SDKWechatBtn addGestureRecognizer:tap];
    }
    return _SDKWechatBtn;
}

- (UIImageView *)SDKFBBtn
{
    if (!_SDKFBBtn) {
        _SDKFBBtn = [[UIImageView alloc] initWithFrame:CGRectMake(LoginVC_X + Cell_H, 0, Cell_H, Cell_H)];
        _SDKFBBtn.image = [UIImage imageNamed:@"login_btn_fb"];
        _SDKFBBtn.left = UI_SCREEN_WIDTH - LoginVC_X - 2 * Cell_H;
        CGFloat space = Cell_H;
        if (IS_IPHONE5 || IS_IPHONE4) space = 24.f;
        _SDKFBBtn.top = self.SDKTopLine.bottom + space;
        _SDKFBBtn.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(FaceBookLogin)];
        [_SDKFBBtn addGestureRecognizer:tap];
    }
    return _SDKFBBtn;
}

// 点击注册新用户
- (void)btnRegisterClick:(id)button
{
    NSString *areaCode = [self.accountView getAreaCode];
    NSString *account = [self.accountView getAccount];
    [self registerActionWithAreaCode:areaCode andMobile:account];
}

// 点击登录
- (void)btnLoginClick:(id)sender
{
    NSString *areaCode = [self.accountView getAreaCode];
    NSString *account = [self.accountView getAccount];
    NSString *password = [self.passwordView getPassword];
    [self showProcessingHud:@"..."];
    [self loginActionWithAreaCode:areaCode andMobile:account andPwd:password];
}

// 点击忘记密码
- (void)btnForgotPwdClick:(id)sender
{
    NSString *areaCode = [self.accountView getAreaCode];
    NSString *account = [self.accountView getAccount];
    [self fogotActionWithAreaCode:areaCode andMobile:account];
}

// 微信登录
- (void)WechatLogin
{

}

// FaceBook登录
- (void)FaceBookLogin
{

}

#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp
{

}

#pragma mark - 用户输入手机号，自动匹配沙盒中保存的用户头像和名字
- (void)fixAvatarAndNameWithAreaCode:(NSString *)areaCode andMobile:(NSString *)mobile
{

}

@end
